package com.lh.tams.util.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库连接工具
 * 
 * @author superchao
 * 
 */
public class ConnUtil {
	/** oracle */
	private static final String PROP_FILE="/oracle.properties";

	/** 数据库连接URL */
	private static String DB_URL;

	/** 数据库连接驱动 */
	private static String DB_DRIVER;

	/** 数据库用户名 */
	private static String DB_USERNAME;

	/** 数据库密码 */
	private static String DB_PASSWORD;

	private static ConnUtil connUtil = null;

	static{
		
	}
	
	/**
	 * 构造函数，必须是private
	 */
	private ConnUtil() {
		init();
	}
	
	private void init(){
		//初始化
		Properties props=new Properties();
		try {
			props.load(ConnUtil.class.getResourceAsStream(PROP_FILE));
			DB_URL=props.getProperty("db.url");
			DB_DRIVER=props.getProperty("db.driver");
			DB_USERNAME=props.getProperty("db.username");
			DB_PASSWORD=props.getProperty("db.password");
		} catch (IOException e) {
			System.out.println("读取oralce配置文件出错！");
		}
	}

	/**
	 * 连接数据库
	 * 
	 * @return 数据库连接对象
	 * @throws Exception
	 */
	public Connection getCon() throws Exception {
		Connection con = null;
		try {
			Class.forName(DB_DRIVER);
			con = DriverManager.getConnection(DB_URL,DB_USERNAME,DB_PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("获取数据库连接失败：" + e.getMessage());
		}
		return con;
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param rs
	 * @param stmt
	 * @param con
	 * @throws Exception
	 */
	public static void closeCon(ResultSet rs, Statement stmt, Connection con)
			throws RuntimeException {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("数据库连接关闭失败：" + e.getMessage());
		}
	}

	/**
	 * 获得数据库连接工具类
	 * 
	 * @return
	 */
	public static ConnUtil newInstance() {
		if (connUtil == null) {
			connUtil = new ConnUtil();
		}
		return connUtil;
	}
}
